
import {
    markerInfo,
    ANIMATION_DURATION,
    MAX_TRAIL_POINTS,
    CAMERA_UPDATE_INTERVAL,
    lerp,
    calculateBearing,
    simplifyTrail,
    getIds,
    setIds,
    getIsTrackingEnabled,
    setIsTrackingEnabled,
    getTrackingId,
    setTrackingId,
    getLastCameraUpdateTime,
    setLastCameraUpdateTime,
    realTimeLayer
} from './realtimeTrackUtil';
import {
    createPopup,
    updatePopup,
    updatePopupPositition,
    closePopup,
} from "../popup/index";
import { LayerConfig, addLayer, LayerType, removeLayer } from "../layer/layerManage.ts";
import { getLayerManagerState } from "../layer/layerManagerState.ts";
// 过滤添加还是修改位置
export const filterAddOrModify = (map: any, data: any) => {
    const { id, positions, info } = data;
    const currentIds = getIds();

    if (currentIds.includes(id)) {
        // 如果 ID 存在，则修改位置
        const previousPositions = markerInfo[id].positions;
        moveMarker(map, id, previousPositions, positions, ANIMATION_DURATION, info);
        markerInfo[id].positions = positions; // 更新上一帧位置
    } else {
        // 如果 ID 不存在，则添加标记
        currentIds.push(id);
        setIds(currentIds);
        addMarker(map, data, info);
        markerInfo[id] = { positions, trail: [], trailEnabled: false, popup: null }; // 存储标记信息和航迹线
    }
};

// 添加标记
export const addMarker = (map: any, data: any, info: any) => {
    const { id, positions } = data;

    // 添加标记的 GeoJSON 数据源
    const source = {
        type: 'geojson',
        data: {
            type: 'FeatureCollection',
            features: [
                {
                    type: 'Feature',
                    geometry: {
                        type: 'Point',
                        coordinates: positions,
                    },
                    properties: { ...info },
                },
            ],
        },
    }
    const layer: LayerConfig = {
        id: `marker-${id}`,
        type: LayerType.Symbol,
        source: source,
        layout: {
            'icon-image': 'airport-15', // 使用 Mapbox 自带的图标
            'icon-rotate': 0,
            'icon-rotation-alignment': 'map',
            'icon-allow-overlap': true,
            'icon-ignore-placement': true,
            'icon-size': 1,
        },
    }
    // 添加标记的 symbol 图层
    // map.addLayer();
    addLayer(getLayerManagerState(map), layer)
};

// 移动标记
export const moveMarker = (map: mapboxgl.Map, id: string, start: [number, number], end: [number, number], duration: number, info: any) => {
    let startTime: number | null = null;

    const animate = (timestamp: number) => {
        const currentIds = getIds();
        if (!currentIds.includes(id)) { return }
        if (!startTime) startTime = timestamp;
        const progress = timestamp - startTime;
        const fraction = Math.min(progress / duration, 1);

        const currentPosition = lerp(start, end, fraction);

        // 更新标记的位置
        const markerSource = map.getSource(`marker-${id}`) as mapboxgl.GeoJSONSource;
        if (markerSource) {
            markerSource.setData({
                type: 'FeatureCollection',
                features: [
                    {
                        type: 'Feature',
                        geometry: {
                            type: 'Point',
                            coordinates: currentPosition,
                        },
                        properties: { ...info },
                    },
                ],
            });
        }

        // 更新标记的朝向
        const bearing = calculateBearing(start, end);
        map.setLayoutProperty(`marker-${id}`, 'icon-rotate', bearing);

        // 更新航迹线
        if (markerInfo[id].trailEnabled) {
            const trail = markerInfo[id].trail;
            trail.push(currentPosition);
            if (trail.length > MAX_TRAIL_POINTS) {
                trail.shift();
            }
            // 简化航迹线（保留关键点）
            const simplifiedTrail = simplifyTrail(trail);
            const trailSource = map.getSource(`trail-${id}`) as mapboxgl.GeoJSONSource;
            if (trailSource) {
                trailSource.setData({
                    type: 'FeatureCollection',
                    features: [
                        {
                            type: 'Feature',
                            geometry: {
                                type: 'LineString',
                                coordinates: simplifiedTrail,
                            },
                            properties: {},
                        },
                    ],
                });
            }
        }

        // 更新 Popup 的位置和内容
        if (markerInfo[id].popup) {
            info.coordinates = [currentPosition[0], currentPosition[1]];
            updatePopupPositition(`popup-${id}`, currentPosition);
            updatePopup(markerInfo[id].popup, realTimeLayer(info));
        }

        // 更新相机位置（如果启用了追踪）
        if (getIsTrackingEnabled() && getTrackingId() === id) {
            const now = Date.now();
            if (now - getLastCameraUpdateTime() >= CAMERA_UPDATE_INTERVAL) {
                map.flyTo({
                    center: currentPosition,
                    speed: 0.5, // 控制相机移动速度
                    curve: 1, // 平滑移动
                    essential: true, // 确保动画不会被中断
                });
                setLastCameraUpdateTime(now);
            }
        }

        if (fraction < 1) {
            requestAnimationFrame(animate);
        }
    };

    requestAnimationFrame(animate);
};

// 移除标记和航迹线
export const removeMarker = (map: mapboxgl.Map, id: string) => {
    const currentIds = getIds();
    if (currentIds.includes(id)) {
        removeLayer(getLayerManagerState(map), `marker-${id}`)
        removeLayer(getLayerManagerState(map), `trail-${id}`)
        // 移除 Popup
        if (markerInfo[id].popup) {
            markerInfo[id].popup.remove();
        }
        const newIds = currentIds.filter(existingId => existingId !== id);
        setIds(newIds);
        delete markerInfo[id];
    }
};

// 动态加载或移除航迹线
export const toggleTrailVisibility = (map: mapboxgl.Map, id: any, isVisible: boolean) => {
    const currentIds = getIds();
    if (currentIds.includes(id)) {
        if (isVisible) {
            // 如果航迹线未加载，则加载航迹线
            const source = {
                type: 'geojson',
                data: {
                    type: 'FeatureCollection',
                    features: [
                        {
                            type: 'Feature',
                            geometry: {
                                type: 'LineString',
                                coordinates: [],
                            },
                            properties: {},
                        },
                    ],
                },
            }
            const layer: LayerConfig = {
                id: `trail-${id}`,
                type: LayerType.Line,
                source: source,
                paint: {
                    'line-color': '#FF0000', // 航迹线颜色
                    'line-width': 2, // 航迹线宽度
                },
            }
            // 添加航迹线的 line 图层，并插入到飞机图层下方
  
            addLayer(getLayerManagerState(map), layer)
            
            // 标记航迹线为启用状态
            markerInfo[id].trailEnabled = true;

            // 将 Popup 存储在 markerInfo 中
            markerInfo[id].popup = createPopup(map, `popup-${id}`, getMarkerPosition(id), realTimeLayer({}));

            // 相机追踪
            // toggleCameraTracking(map, id);
        } else {
            // 如果航迹线已加载，则移除航迹线
            removeLayer(getLayerManagerState(map), `trail-${id}`);


            // 标记航迹线为禁用状态
            markerInfo[id].trailEnabled = false;

            // 禁用 Popup
            closePopup(`popup-${id}`);

        }
    }
};

// 获取当前飞机的坐标信息
export const getMarkerPosition = (id: any): [number, number] | null => {
    const currentIds = getIds();
    if (currentIds.includes(id) && markerInfo[id]) {
        return markerInfo[id].positions; // 返回当前坐标
    }
    return null; // 如果 ID 不存在，返回 null
};

// 启用或禁用相机追踪
export const toggleCameraTracking = (map: mapboxgl.Map, id: string | null) => {
    setIsTrackingEnabled(!!id); // 启用或禁用追踪
    setTrackingId(id); // 设置当前追踪的标记 ID
};

// 修改航迹线样式
export const updateTrailStyle = (map: mapboxgl.Map, id: string, color?: string, width?: number) => {
    const trailLayerId = `trail-${id}`;
    if (map.getLayer(trailLayerId)) {
        if (color) {
            map.setPaintProperty(trailLayerId, 'line-color', color);
        }
        if (width) {
            map.setPaintProperty(trailLayerId, 'line-width', width);
        }
    }
};